import { BASE_URL, TOKEN } from '@/constants'
import { useUserStore } from "@/store/user"

const userStore = useUserStore()

export const fetch = (options, noLoading = false) => {
	if(!noLoading) {
		// 加载中
		uni.showLoading({
			title: "加载中",
			mask: true
		})
	}
	return new Promise((resolve, reject) => {
		uni.request({
			url: BASE_URL + options.url,
			method: options.method || 'POST',
      data: options.data,
       /* || {
        page: 1,
        pageSize: 30
      }, */
      // responseType: options.responseType || 'text',
			header: options.header || {
				'Content-Type': 'application/json',
				// 切割使用token 不要|与时间差
				// 'nld_login_token': uni.getStorageSync('nld_login_token'),
			},
			// #ifdef H5
			withCredentials: true, // 允许携带cookies
			// #endif
			success: (res) => {
				const result: any = res.data
				switch (result.status) {
					case 1: // 成功
						if (result.msg) {
							uni.showToast({
								title: result.msg
							});
						}
						resolve(result)
						break
					case 10001: // needLogin
						if (result.msg) {
							uni.showToast({
								title: result.msg,
								icon: 'none'
							})
						}
						// 删除token 并跳转登录页
						userStore.setToken()
						setTimeout(() => {
							uni.reLaunch({
								url: "/pages/login/login"
							})
						}, 1000)
						break
					default:
						if (result.msg) {
							uni.showToast({
								title: result.msg || '获取数据失败',
								icon: 'error'
							})
						}
          }
				/* if (res.data.status !== 1) {
					if (res.data.status === 10001) {
						uni.showToast({
							title: '需要登录',
							icon: 'none'
						})
						// 登录失效后清除token
						uni.removeStorageSync('token')
						uni.removeStorageSync('nld_login_token')
						// 登录失效后则跳转至登录页
						setTimeout(() => {
							uni.reLaunch({
								url: "/pages/login/login"
							})
						}, 1000)
					} else {
						uni.showToast({
							title: res.data.msg || '获取数据失败',
							icon: 'none'
						})
					}
					return
				} */
				resolve(res.data)
			},
			fail: (err) => {
				uni.showToast({
					title: err || '请求接口失败',
					icon: 'error'
				})
				reject(err)
			},
			complete() {
				uni.hideLoading()
			}
		})
	})
}
